#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {
        int n = matrix.size();
        if (n == 1)return matrix[0][0];
        vector<vector<int>>f(n + 1, vector<int>(n + 1, INT_MAX));
        for (int i = 0; i < n; i++) {
            f[0][i] = matrix[0][i];
        }

        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (j == 0) {
                    f[i][j] = min(f[i - 1][j], f[i - 1][j + 1]) + matrix[i][j];
                }
                else {
                    f[i][j] = min({ f[i - 1][j],f[i - 1][j - 1],f[i - 1][j + 1] }) + matrix[i][j];
                }
            }
        }
        int ans = INT_MAX;
        for (int i = 0; i < n; i++) {
            ans = min(ans, f[n - 1][i]);

        }
        return ans;
    }
};